package com.gitee.gateway.handlers;

import com.gitee.gateway.beans.DemoBean;
import com.gitee.gateway.core.security.CacheRateLimiterRegistry;
import com.gitee.gateway.dao.DemoDao;
import com.gitee.gateway.demo.DemoService;
import com.gitee.service.openapi.FunctionHandler;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import io.vertx.core.Future;
import io.vertx.ext.web.RoutingContext;

import java.time.Duration;
import java.util.List;
import java.util.function.Function;

/**
 * 系统全局配置管理接口
 */
public class HelloHandler implements FunctionHandler {

    private final RateLimiterRegistry registry;
    private final String action;

    public HelloHandler(String action) {
        this.action = action;
        //设置一个每分钟最多调用100次的限流器
        RateLimiterConfig config = RateLimiterConfig.custom()
                .limitRefreshPeriod(Duration.ofMinutes(1))
                .limitForPeriod(100)
                .timeoutDuration(Duration.ofMillis(0))
                .build();
        this.registry = new CacheRateLimiterRegistry("search", config);

    }

    @Override
    public Function<RoutingContext, ?> mapping(RoutingContext context) {
        return switch (action) {
            case "say" -> this::sayHello;
            case "dbTest" -> this::dbTest;
            case "serviceTest" -> this::serviceTest;
            default -> null;
        };
    }

    String sayHello(RoutingContext context) {
        String name = context.request().getParam("name");
        return STR."Hello \{name == null ? "World" : name}";
    }

    List<DemoBean> dbTest(RoutingContext context) {
        return USE(DemoDao.class).list();
    }

    Future<String> serviceTest(RoutingContext context) {
        String key = context.request().remoteAddress().hostAddress();
        DemoService proxy = DemoService.createProxy(context.vertx());
        //根据 ip 对后端服务进行访问限流
        return checkLimiterAndCall(this.registry, key, (ip) -> proxy.sayHello("Service"));
    }

}
